import "reflect-metadata";

interface ModuleMetadata {
  controllers?: Function[];
  providers?: any[];
  exports?: any[];
  imports?: any[];
}
/**
 * @description 定义模块装饰器
 * @param metadata { ModuleMetadata }
 * @returns
 */
export function Module(metadata?: ModuleMetadata): ClassDecorator {
  return function (target: Function) {
    Reflect.defineMetadata("isModule", true, target);
    defineModule(target, metadata.controllers);
    Reflect.defineMetadata("controllers", metadata.controllers, target);
    // let providers = (metadata.providers ?? []).map((provider) => {
    //   if (provider instanceof Function) {
    //     return provider;
    //   } else if (provider?.useClass instanceof Function) {
    //     return provider.useClass;
    //   } else {
    //     return null;
    //   }
    // });
    // defineModule(target, providers);
    defineModule(target, metadata.providers ?? []);
    Reflect.defineMetadata("providers", metadata.providers, target);
    Reflect.defineMetadata("exports", metadata.exports, target);
    Reflect.defineMetadata("imports", metadata.imports, target);
  };
}

export function defineModule(nestModule, targets = []) {
  // console.log("defineModule", nestModule, targets);
  if (!targets.length) return;
  // 给每一个模块添加 他属于哪个模块的元数据
  targets.forEach((target) => {
    Reflect.defineMetadata("nestModule", nestModule, target);
  });
}

export function isGlobal() {
  return function (target: Function) {
    Reflect.defineMetadata("isGlobal", true, target);
  };
}

export interface DynamicModule extends ModuleMetadata {
  module: Function;
}
